package com.walsai.pcsys.web.controller;

import java.io.File;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.walsai.pcsys.core.model.Problem;
import com.walsai.pcsys.core.service.ProblemManager;

public class AdminSubmitProblemController extends SimpleFormController {

	private ProblemManager problemManager;

	public void setProblemManager(ProblemManager problemManager) {
		this.problemManager = problemManager;
	}

	protected void initBinder(HttpServletRequest req,
			ServletRequestDataBinder binder) throws ServletException {
		binder.registerCustomEditor(byte[].class,
				new ByteArrayMultipartFileEditor());
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		Problem p = (Problem) command;
		Problem pSaved = this.problemManager.save(p);
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile problemFile = multipartRequest
					.getFile("descriptionFile");
			File destination = null;
			destination = new File("target/web-1.0-SNAPSHOT/problem/"+pSaved.getId() + ".pdf");
			problemFile.transferTo(destination);
			MultipartFile inputFile = multipartRequest.getFile("inputFile");
			destination = new File("target/web-1.0-SNAPSHOT/input/"+pSaved.getId() + ".in");
			inputFile.transferTo(destination);
			MultipartFile outputFile = multipartRequest.getFile("outputFile");
			destination = new File("target/web-1.0-SNAPSHOT/output/"+pSaved.getId() + ".out");
			outputFile.transferTo(destination);
			return new ModelAndView(this.getSuccessView());
		} catch (Exception e) {
			this.problemManager.remove(pSaved.getId());
			return new ModelAndView("failed");
		}

	}

}
